<template>
  <div>
    <Content title="用户" :subTitle="isNew?'新建':'编辑'" path="/user">
      <div slot="body">
        <div style="padding-left: 20px">
          <p style="font-size: 20px">用户</p>
          <el-form :model="form" label-position="left" :rules="rules" ref="form" label-width="140px" class="user-form">
            <el-form-item label="账号" prop="name" class="my-form-item">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass" class="my-form-item">
              <el-input v-model="form.pass" type="password" placeholder="密码（无需修改请留空）"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" class="my-form-item">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone" class="my-form-item">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nick" class="my-form-item">
              <el-input v-model="form.nick"></el-input>
            </el-form-item>
            <!--<el-form-item label="头像" prop="nick">-->
            <!--<el-input v-model="form.avatar"></el-input>-->
            <!--</el-form-item>-->
            <el-form-item label="生日" prop="birthday" class="my-form-item">
              <el-date-picker type="date" placeholder="选择生日" v-model="form.birthday"
                              format="yyyy-MM-dd" style="width: 100%"
                              value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
            <el-form-item label="用户类型" prop="roleId" class="my-form-item">
              <el-radio-group v-model="form.roleId">
                <el-radio label="0">一般用户</el-radio>
                <el-radio :disabled="isNormal" label="-1">超级管理员</el-radio>
              </el-radio-group>
              <span v-if="isNormal" style="color:#F56C6C">&nbsp;&nbsp;&nbsp;一般用户不能选择超级管理员角色</span>
            </el-form-item>
            <el-form-item label="部门" prop="departmentId" class="my-form-item">
              <el-cascader :options="departments"
                           change-on-select clearable
                           :props="defaultProps" v-model="form.departmentIds"></el-cascader>
            </el-form-item>
            <el-form-item label="性别" prop="gender" class="my-form-item">
              <el-radio-group v-model="form.gender">
                <el-radio label="1">男</el-radio>
                <el-radio label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status" class="my-form-item">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option label="正常" value="1"></el-option>
                <el-option label="失效" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最近访问时间" prop="visited" class="my-form-item">
              <el-input v-model="form.visited" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="创建时间" prop="created" class="my-form-item">
              <el-input v-model="form.created" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="更新时间" prop="updated" class="my-form-item">
              <el-input v-model="form.updated" disabled="disabled"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </Content>
    <div style="padding: 15px">
      <router-link to="/user">
        <el-button plain round type="info" icon="el-icon-back">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="submitForm('form')" icon="el-icon-circle-check">保存</el-button>
    </div>
  </div>
</template>

<script>
  import util from '../../utils/util'
  import {User} from '../../utils/resource'
  import {showSaveResponse, validFieldExists, validateForm, SessionStorageUtil} from '../../utils/element-helper'

  import Content from '../../components/Content.vue'
  import {mapState, mapActions} from 'vuex'


  export default {
    name: 'userDetail',
    components: {
      Content,
    },
    data() {
      return {
        isNormal: false,//非普通用户才能选择角色
        isNew: true, // new true or  edit false
        initForm: {},// for edit
        loading: false,
        form: {
          roleId: "0",
          gender: "1",
          status: "1",
          departmentIds: [],
        },
        defaultProps: {
          value: "id",
          label: 'name',
          children: 'children'
        },
        rules: {
          name: [
            {required: true, message: '账号不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          email: [
            {required: true, message: '邮箱地址不能为空', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          phone: [
            {required: true, message: '手机号码不能为空', trigger: 'blur'},
            {pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码'},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          pass: [
            {min: 5, max: 25, message: '密码长度在 5 到 25 位之间', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                this.validatePass(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          departmentId: [
            {required: true, message: '部门不能为空', trigger: 'blur'},
          ],
        },
      }
    },
    created() {
      let id = this.$route.params.id
      this.isNew = (id == 'new')
      if (!this.isNew) {
        this.loadUser()
      }
    },
    computed: {
      ...mapState("department", [
        "departments",
      ]),
    },
    methods: {
      async loadUser() {
        let id = this.$route.params.id
        let res = await User.get(id)
        res.data.roleId = String(res.data.roleId)
        res.data.gender = String(res.data.gender)
        res.data.status = String(res.data.status)
        res.data.departmentIds = util.getTreePath(this.departments, res.data.departmentId)
        res.data.pass = ''
        let user = SessionStorageUtil.getItem("user")
        if (user.roleId === -1) {
          this.isNormal = false
        } else {
          this.isNormal = true
        }
        this.form = res.data
        this.initForm = res.data
      },
      submitForm(formName) {
        this.form.departmentId = this.form.departmentIds[this.form.departmentIds.length - 1]
        return validateForm(this, formName, () => {
          let tempFrom = Object.assign({}, this.form)
          //不修改密码需要将密码清空
          if (tempFrom.pass === '') {
            delete tempFrom['pass']
          }
          showSaveResponse(this, () => User.save(tempFrom, this.isNew ? 'post' : 'put'), (res) => this.$router.back())
        })
      },
      validateExists(rule, value, callback) {
        validFieldExists(rule, value, callback, this.initForm[rule.field] != value || this.isNew, (rule, value) => User.exists(rule, value))
      },
      validatePass(rule, value, callback) {
        if (this.isNew && (value === '' || value === undefined)) {
          callback(new Error("密码不能为空"))
        } else {
          callback()
        }
      },
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .user-form {
    width: 90%;
  }

  .my-form-item {
    max-width: 600px;
  }

</style>
<style>
  .my-form-input {
    max-width: 330px;
  }
</style>
